package cc.comac.mom.datahandlers.entity;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cc.comac.mom.bean.*;
import cc.comac.mom.dao.entity.*;
import cc.comac.mom.util.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cc.comac.mom.bean.base.LimitPageBean;
import cc.comac.mom.entity.EquipBenchmarkItemEntity;
import cc.comac.mom.entity.EquipMaintainPlanEntity;
import cc.comac.mom.entity.EquipMaintainSpareReplaceEntity;
import cc.comac.mom.entity.EquipMaintainWorkOrderEntity;
import cc.comac.mom.entity.EquipMaintainWorkOrderExecutionEntity;
import cc.comac.mom.entity.EquipSparePartMasterDataEntity;

@Component
@Transactional
public class EquipMaintainPlanDataHandler extends ServiceImpl<EquipMaintainPlanDao, EquipMaintainPlanEntity> {

	@Autowired
	private EquipMaintainPlanDao equipMaintainPlanDao;
	@Autowired
	private EquipMaintainWorkOrderDao equipMaintainWorkOrderDao;

	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;

	@Autowired
	private UniversalNumberGenerationDataHandler universalNumberGenerationDataHandler;

	@Autowired
	private EquipMaintainWorkOrderDataHandler equipMaintainWorkOrderDataHandler;

	@Autowired
	private EquipMaintainWorkOrderExecutionDataHandler equipMaintainWorkOrderExecutionDataHandler;

	@Autowired
	private EquipBenchmarkItemDao equipBenchmarkItemDao;
	@Autowired
	private EquipBenchmarkDao equipBenchmarkDao;
	@Autowired
	private EquipSparePartMasterDataDao equipSparePartMasterDataDao;

	@Autowired
	private EquipMaintainSpareReplaceDataHandler equipMaintainSpareReplaceDataHandler;


	public ResultBean insertMaintainPlan(List<EquipMaintainPlan> equipMaintainPlan) {
		ResultBean resultBean = new ResultBean(true);
		for (EquipMaintainPlan equipMaintainPlan2 : equipMaintainPlan) {
			insertMaintainPlan(equipMaintainPlan2);
		}
		return resultBean;
	}

	// 新增保养数据
	public ResultBean insertMaintainPlan(EquipMaintainPlan equipMaintainPlan) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainPlanEntity innerData = equipMaintainPlan.getInnerData();
		LocalDateTime firstPlanDateStart = TimeUtil.fomatDateToLocalDateTime(innerData.getFirstPlanDateStart());
		// 获取循环周期转换成小时
		int cycle = FrequencyUtil.getCycleDataToHouse(innerData.getCycleType(),innerData.getCycle());
		// 获取保养频率转换成小时
		int maintainFrequency = FrequencyUtil.getCycleDataToHouse(innerData.getMaintainFrequencyType(),innerData.getMaintainFrequency());
		if (cycle < maintainFrequency) {
			throw new RuntimeException("循环周期必须大于保养频率");
		}
		/*QueryWrapper<EquipMaintainPlanEntity> queryWrapper = new QueryWrapper<EquipMaintainPlanEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("dev_number", innerData.getDevNumber());
		queryWrapper.eq("grade", innerData.getGrade());
		EquipMaintainPlanEntity selectOne = equipMaintainPlanDao.selectOne(queryWrapper);
		if (selectOne != null) {
			LocalDateTime cycleDataToDateTime = FrequencyUtil.getCycleDataToLocalDateTime(innerData.getCycleType(),innerData.getCycle(), firstPlanDateStart);
			if (cycleDataToDateTime.isBefore(TimeUtil.fomatDateToLocalDateTime(innerData.getFirstPlanDateStart()))) {
				throw new RuntimeException("当前设备已有保养计划至" + cycleDataToDateTime.getYear() + "/"
						+ cycleDataToDateTime.getMonthValue() + "/" + cycleDataToDateTime.getDayOfMonth() + "无法新增");

			} else {
				throw new RuntimeException("当前设备" + innerData.getGrade() + "等级" + innerData.getGrade() + "已存在！");
			}
		}*/
		Date date=equipMaintainWorkOrderDao.selectMaxPlanDateEnd(innerData.getDevNumber(),innerData.getGrade());
		if(date!=null&&!TimeUtil.fomatDateToLocalDateTime(date).isBefore(TimeUtil.fomatDateToLocalDateTime(innerData.getFirstPlanDateStart()))){
			LocalDateTime cycleDataToDateTime=TimeUtil.fomatDateToLocalDateTime(date);
			throw new RuntimeException("当前设备" + innerData.getDevNumber()+innerData.getDevName() + "等级" + innerData.getGrade() + "已保养计划至" + cycleDataToDateTime.getYear() + "/"
					+ cycleDataToDateTime.getMonthValue() + "/" + cycleDataToDateTime.getDayOfMonth() + "无法新增");
		}
		String numberGeneration = universalNumberGenerationDataHandler
				.numberGeneration(universalNumberGenerationDataHandler.getMaintainPlan());
		innerData.setMaintainPlanNumber(numberGeneration);
		baseEntityDataUtil.setBaseEntityData(innerData);
		equipMaintainPlanDao.insert(innerData);
		return resultBean;
	}

	// 批量删除数据
	public ResultBean batchDeleteByMaintainPlanId(List<EquipMaintainPlan> list) {
		ResultBean resultBean = new ResultBean(true);
		if (list.size() > 0) {
			List<EquipMaintainPlanEntity> entityList = new ArrayList<EquipMaintainPlanEntity>();
			for (EquipMaintainPlan equipMaintainPlan : list) {
				EquipMaintainPlanEntity equipMaintainPlanEntity = new EquipMaintainPlanEntity();
				equipMaintainPlanEntity.setId(equipMaintainPlan.getInnerData().getId());
				equipMaintainPlanEntity.setRowStatus(0);
				baseEntityDataUtil.updateBaseEntityData(equipMaintainPlanEntity);
				entityList.add(equipMaintainPlanEntity);
			}
			updateBatchById(entityList, entityList.size());
		}
		return resultBean;
	}

	// 更新数据通过保养计划主键
	public ResultBean updateByMaintainPlanId(EquipMaintainPlan equipMaintainPlan) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainPlanEntity innerData = equipMaintainPlan.getInnerData();
		baseEntityDataUtil.updateBaseEntityData(innerData);
		if (innerData.getId() == 0) {
			throw new RuntimeException("无法获取保养计划主键！");
		}
		// 获取循环周期转换成小时
		int cycle = FrequencyUtil.getCycleDataToHouse(innerData.getCycleType(),innerData.getCycle());
		// 获取保养频率转换成小时
		int maintainFrequency = FrequencyUtil.getCycleDataToHouse(innerData.getMaintainFrequencyType(),innerData.getMaintainFrequency());
		if (cycle < maintainFrequency) {
			throw new RuntimeException("循环周期必须大于保养频率");
		}
		equipMaintainPlanDao.updateById(innerData);
		return resultBean;
	}

	// 通过条件查询对应数据
	public ResultDev selectBySomeFields(EquipMaintainPlanBean obj) {
		ResultDev resultDev = new ResultDev();
		if (obj.getPageSize() == 0) {
			obj.setPageSize(10);
		}
		obj.setPageNum((obj.getPageNum()-1)*obj.getPageSize());
		List<EquipMaintainPlanBean> list = equipMaintainPlanDao.selectByFields(obj);
		long countByFields = equipMaintainPlanDao.selectCountByFields(obj);

		// 将查询总数除以每页数量后向上取整获取总页数
		double pageCount = Math.ceil((double)countByFields / obj.getPageSize());
		resultDev.setEntityList(list);
		resultDev.setPageCount((int)pageCount);
		resultDev.setTotalQuantity((int)countByFields);
		return resultDev;
	}

	// 改变计划失效状态
	public ResultBean changeEnable(EquipMaintainPlan equipMaintainPlan) {
		ResultBean resultBean = new ResultBean(true);
		EquipMaintainPlanEntity innerData = equipMaintainPlan.getInnerData();
		if (innerData.getId() == 0) {
			throw new RuntimeException("无法获取计划保养主键");
		}
		QueryWrapper<EquipMaintainPlanEntity> queryWrapper = new QueryWrapper<EquipMaintainPlanEntity>();
		queryWrapper.eq("row_status", 1);
		queryWrapper.eq("maintain_plan_id", innerData.getId());
		EquipMaintainPlanEntity selectOne = equipMaintainPlanDao.selectOne(queryWrapper);
		baseEntityDataUtil.updateBaseEntityData(selectOne);
		selectOne.setEnable(innerData.getEnable());
		equipMaintainPlanDao.updateById(selectOne);
		return resultBean;
	}

	// 计划下发生成工单
	public ResultBean planSent(List<EquipMaintainPlan> list) {
		ResultBean resultBean = new ResultBean(true);
		for (EquipMaintainPlan equipMaintainPlan : list) {
			List<EquipMaintainWorkOrderEntity> workOrderList = new ArrayList<EquipMaintainWorkOrderEntity>();
			EquipMaintainPlanEntity equipMaintainPlanEntity = equipMaintainPlan.getInnerData();
			EquipMaintainPlanEntity innerData = equipMaintainPlanDao.selectById(equipMaintainPlanEntity.getId());

			Date date=equipMaintainWorkOrderDao.selectMaxPlanDateEnd(innerData.getDevNumber(),innerData.getGrade());
			if(date!=null&&!TimeUtil.fomatDateToLocalDateTime(date).isBefore(TimeUtil.fomatDateToLocalDateTime(innerData.getFirstPlanDateStart()))){
				LocalDateTime cycleDataToDateTime=TimeUtil.fomatDateToLocalDateTime(date);
				throw new RuntimeException("当前设备" + innerData.getDevNumber()+innerData.getDevName() + "等级" + innerData.getGrade() + "已保养计划至" + cycleDataToDateTime.getYear() + "/"
						+ cycleDataToDateTime.getMonthValue() + "/" + cycleDataToDateTime.getDayOfMonth() + "无法下发");
			}

			//下发完成修改下发计划状态
			innerData.setStatus("1");
			equipMaintainPlanDao.updateById(innerData);
			int frequencyHouse = FrequencyUtil.getCycleDataToHouse(innerData.getMaintainFrequencyType(),innerData.getMaintainFrequency());
			int cycleDataToHouse = FrequencyUtil.getCycleDataToHouse(innerData.getCycleType(),innerData.getCycle());
			int loopFre = (int) Math.ceil(cycleDataToHouse / frequencyHouse);
			if(loopFre==0){
				throw new RuntimeException("频率不能大于周期");
			}
			// 计算执行时长转换成小时
			int cycleDataToHouse2 = FrequencyUtil.getCycleDataToHouse(innerData.getExecutionDurationType(),innerData.getExecutionDuration());
			for (int i = 0; i <= loopFre - 1; i++) {
				EquipMaintainWorkOrderEntity equipMaintainWorkOrderEntity = new EquipMaintainWorkOrderEntity();
				// 计算出计划开始时间
				LocalDateTime plusHours = FrequencyUtil.getAddDataByUnit(innerData.getFirstPlanDateStart(), innerData.getMaintainFrequencyType(), innerData.getMaintainFrequency(), i);
				// 计算出工单发布时的计划开始时间
				//LocalDateTime plusHours = TimeUtil.fomatDateToLocalDateTime(innerData.getFirstPlanDateStart()).plusHours(frequencyHouse*i);
				// 赋值计划开始时间
				equipMaintainWorkOrderEntity.setPlanDateStart(TimeUtil.fomatLocalDateTimeToDate(plusHours));
				// 赋值计划结束时间
				equipMaintainWorkOrderEntity.setPlanDateEnd(TimeUtil.fomatLocalDateTimeToDate(plusHours.plusHours(cycleDataToHouse2)));
				equipMaintainWorkOrderEntity.setActualTeam(innerData.getActualTeam());
				equipMaintainWorkOrderEntity.setActualTeamId(innerData.getActualTeamId());
				equipMaintainWorkOrderEntity.setBenchmarkNumber(innerData.getBenchmarkNumber());
				equipMaintainWorkOrderEntity.setCalendarCode(innerData.getCalendarCode());
				equipMaintainWorkOrderEntity.setCycle(innerData.getCycle());
				equipMaintainWorkOrderEntity.setCycleType(innerData.getCycleType());
				equipMaintainWorkOrderEntity.setUserDepartment(innerData.getUserDepartment());
				equipMaintainWorkOrderEntity.setDevCategoryNumber(innerData.getDevCategoryNumber());
				equipMaintainWorkOrderEntity.setDevCategoryId(innerData.getDevCategoryId());
				equipMaintainWorkOrderEntity.setDevCategoryName(innerData.getDevCategoryName());
				equipMaintainWorkOrderEntity.setDevId(innerData.getDevId());
				equipMaintainWorkOrderEntity.setDevName(innerData.getDevName());
				equipMaintainWorkOrderEntity.setDevNumber(innerData.getDevNumber());
				equipMaintainWorkOrderEntity.setEnable(innerData.getEnable());
				equipMaintainWorkOrderEntity.setExecutionDuration(innerData.getExecutionDuration());
				equipMaintainWorkOrderEntity.setExecutionDurationType(innerData.getExecutionDurationType());
				equipMaintainWorkOrderEntity.setFirstPlanDateStart(innerData.getFirstPlanDateStart());
				equipMaintainWorkOrderEntity.setStatus(MomConstants.EQUIP_MAINTAIN_ORDER_STATUS_DISPATCH);
				equipMaintainWorkOrderEntity.setGrade(innerData.getGrade());
				equipMaintainWorkOrderEntity.setIfCalendar(innerData.getIfCalendar());
				equipMaintainWorkOrderEntity.setLocation(innerData.getLocation());
				equipMaintainWorkOrderEntity.setMaintainCycleName(innerData.getMaintainCycleName());
				equipMaintainWorkOrderEntity.setMaintainFrequency(innerData.getMaintainFrequency());
				equipMaintainWorkOrderEntity.setMaintainFrequencyType(innerData.getMaintainFrequencyType());
				equipMaintainWorkOrderEntity.setMaintainPlanId(innerData.getId());
				equipMaintainWorkOrderEntity.setMaintainPlanNumber(innerData.getMaintainPlanNumber());
				equipMaintainWorkOrderEntity.setBenchmarkId(innerData.getBenchmarkId());
				workOrderList.add(equipMaintainWorkOrderEntity);
			}
			if (workOrderList.size() > 0) {
				List<EquipMaintainWorkOrderExecution> listOrderExe = new ArrayList<EquipMaintainWorkOrderExecution>();
				// 生成保养工单中的备件更换
				ArrayList<EquipMaintainSpareReplaceEntity> replaceEntityList = new ArrayList<EquipMaintainSpareReplaceEntity>();
				// 计划下发生成工单
				equipMaintainWorkOrderDataHandler.batchInsertMaintainWorkOrder(workOrderList);
				// 通过工单生成工单基准数据
				for (EquipMaintainWorkOrderEntity equipMaintainWorkOrderEntity : workOrderList) {
					QueryWrapper<EquipBenchmarkItemEntity> queryWrapper = new QueryWrapper<EquipBenchmarkItemEntity>();
					queryWrapper.eq("row_status", 1);
					queryWrapper.eq("benchmark_id", equipMaintainWorkOrderEntity.getBenchmarkId());
					// 生成工单基准数据
					List<EquipBenchmarkItemEntity> selectList = equipBenchmarkItemDao.selectList(queryWrapper);
					if (selectList.size() > 0) {
						for (EquipBenchmarkItemEntity equipBenchmarkItemEntity : selectList) {
							// 生成基准工单数据
							EquipMaintainWorkOrderExecution equipMaintainWorkOrderExecution = new EquipMaintainWorkOrderExecution();
							EquipMaintainWorkOrderExecutionEntity equipMaintainWorkOrderExecutionEntity = new EquipMaintainWorkOrderExecutionEntity();
							equipMaintainWorkOrderExecution.setInnerData(equipMaintainWorkOrderExecutionEntity);
							equipMaintainWorkOrderExecutionEntity.setMaintainWorkOrderId(equipMaintainWorkOrderEntity.getId());
							equipMaintainWorkOrderExecutionEntity.setMaintainWorkOrderNumber(equipMaintainWorkOrderEntity.getOrderNumber());
							equipMaintainWorkOrderExecutionEntity.setMaintainWorkOrderNumber(equipMaintainWorkOrderEntity.getOrderNumber());
							equipMaintainWorkOrderExecutionEntity.setBenchmarkId(equipMaintainWorkOrderEntity.getBenchmarkId());
							equipMaintainWorkOrderExecutionEntity.setBenchmarkNumber(equipMaintainWorkOrderEntity.getBenchmarkNumber());
							equipMaintainWorkOrderExecutionEntity.setBenchmarkItemId(equipBenchmarkItemEntity.getId());
							equipMaintainWorkOrderExecutionEntity.setExecutionDuration(equipMaintainWorkOrderEntity.getExecutionDuration());
							equipMaintainWorkOrderExecutionEntity.setExecutionDurationType(equipMaintainWorkOrderEntity.getExecutionDurationType());
							//equipMaintainWorkOrderExecutionEntity.setPictureAttachmentGroupId(baseEntityDataUtil.getGenerateId());
							equipMaintainWorkOrderExecutionEntity.setExecutionStatus("0");
							equipMaintainWorkOrderExecutionEntity.setExecutionDurationType(equipMaintainWorkOrderEntity.getExecutionDurationType());
							listOrderExe.add(equipMaintainWorkOrderExecution);

							// 新增工单备件更换数据（默认为基准数据）
							QueryWrapper<EquipSparePartMasterDataEntity> queryWrapper2 = new QueryWrapper<EquipSparePartMasterDataEntity>();
							queryWrapper2.eq("row_status", 1);
							queryWrapper2.eq("spare_part_number", equipBenchmarkItemEntity.getPartsNumber());
							EquipSparePartMasterDataEntity selectOne = equipSparePartMasterDataDao.selectOne(queryWrapper2);
							if(selectOne!=null) {
								EquipMaintainSpareReplaceEntity equipMaintainSpareReplaceEntity = new EquipMaintainSpareReplaceEntity();
								equipMaintainSpareReplaceEntity.setDevName(equipMaintainWorkOrderEntity.getDevName());
								equipMaintainSpareReplaceEntity.setDevNumber(equipMaintainWorkOrderEntity.getDevNumber());
								equipMaintainSpareReplaceEntity.setOrderNumber(equipMaintainWorkOrderEntity.getOrderNumber());
								equipMaintainSpareReplaceEntity.setReplaceQuantity(new BigDecimal(equipBenchmarkItemEntity.getPartsAmount()));
								equipMaintainSpareReplaceEntity.setSparePartId(selectOne.getId());
								equipMaintainSpareReplaceEntity.setSparePartName(selectOne.getSparePartName());
								equipMaintainSpareReplaceEntity.setSparePartNumber(selectOne.getSparePartNumber());
								equipMaintainSpareReplaceEntity.setSparePartType(selectOne.getSparePartType());
								equipMaintainSpareReplaceEntity.setSparePartModel(selectOne.getSparePartModel());
								equipMaintainSpareReplaceEntity.setUserDepartment(equipMaintainWorkOrderEntity.getUserDepartment());
								baseEntityDataUtil.setBaseEntityData(equipMaintainSpareReplaceEntity);
								replaceEntityList.add(equipMaintainSpareReplaceEntity);
							}
						}
					}
				}
				if(listOrderExe.size() > 0) {
					equipMaintainWorkOrderExecutionDataHandler.batchInsertMaintainWorkOrderExecution(listOrderExe);
				}
				if (replaceEntityList.size() > 0) {
					equipMaintainSpareReplaceDataHandler.saveBatch(replaceEntityList, replaceEntityList.size());
				}
			}
		}
		return resultBean;
	}

	// 保养中查询基准数据
	public ResultBean selectBenchmarkByLocation(EquipMaintainPlan equipMaintainPlan) {
		ResultBean resultBean = new ResultBean(true);
		if (equipMaintainPlan.getPageNum() == 0) {
			equipMaintainPlan.setPageNum(1);
		}
		if (equipMaintainPlan.getPageSize() == 0) {
			equipMaintainPlan.setPageSize(10);
		}
		String devCategoryName = "";
		if (StringUtils.isNotEmpty(equipMaintainPlan.getInnerData().getDevCategoryName())) {
			devCategoryName = equipMaintainPlan.getInnerData().getDevCategoryName();
		}
		int pageNum = (equipMaintainPlan.getPageNum()-1)*equipMaintainPlan.getPageSize();
		List<EquipBenchmarkSelectBean> list = equipBenchmarkDao.selectByLocation(pageNum,equipMaintainPlan.getPageSize(),devCategoryName,equipMaintainPlan.getWorkShop());

		int total = equipBenchmarkDao.selectCountByLocation(devCategoryName, equipMaintainPlan.getWorkShop());
		LimitPageBean<EquipBenchmarkSelectBean> limitPageBean = new LimitPageBean<EquipBenchmarkSelectBean>();
		limitPageBean.setEntityList(list);
		limitPageBean.setPageNum(pageNum);
		limitPageBean.setPageSize(equipMaintainPlan.getPageSize());
		limitPageBean.setTotalQuantity(total);
		limitPageBean.setPageCount((int)Math.ceil(total/equipMaintainPlan.getPageSize()));
		resultBean.setObject(limitPageBean);
		return resultBean;
	}


}
